package com.food.controller;

import com.food.common.Result;
import com.food.model.UserProfile;
import com.food.model.UserGoal;
import com.food.service.UserService;
import com.food.service.FileService;
import com.food.mapper.UserMapper;
import com.food.dto.UserRegisterDTO;
import com.food.dto.UserLoginDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.http.MediaType;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import javax.validation.Valid;

@Api(tags = "用户管理")
@RestController
@RequestMapping("/api/user")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private FileService fileService;
    
    @Autowired
    private UserMapper userMapper;

    @ApiOperation("用户注册")
    @PostMapping("/register")
    public Result<?> register(@Valid @RequestBody UserRegisterDTO registerDTO) {
        return userService.register(registerDTO);
    }

    @ApiOperation("用户登录")
    @PostMapping("/login")
    public Result<?> login(@RequestBody UserLoginDTO loginDTO) {
        return userService.login(loginDTO);
    }

    @GetMapping("/profile")
    public Result<?> getProfile(@RequestParam Integer userId) {
        return userService.getProfile(userId);
    }

    @PutMapping("/profile")
    public Result<?> updateProfile(@RequestBody UserProfile profile) {
        return userService.updateProfile(profile);
    }

    @PutMapping("/password")
    public Result<?> updatePassword(
            @RequestParam Integer userId,
            @RequestParam String oldPassword,
            @RequestParam String newPassword) {
        return userService.updatePassword(userId, oldPassword, newPassword);
    }

    @ApiOperation("更新用户头像")
    @PostMapping(value = "/avatar", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Result<?> updateAvatar(
            @RequestParam Integer userId,
            @ApiParam(value = "头像文件", required = true)
            @RequestPart("file") MultipartFile file) {
        try {
            String avatarUrl = fileService.uploadFile(file);
            userMapper.updateAvatar(userId, avatarUrl);
            return Result.success(avatarUrl);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("上传失败：" + e.getMessage());
        }
    }

    @PostMapping("/avatar/preset")
    public Result<?> updateAvatarByPreset(
            @RequestParam Integer userId,
            @RequestParam String avatarName) {
        try {
            String avatarUrl = "/images/avatar/" + avatarName;
            userMapper.updateAvatar(userId, avatarUrl);
            return Result.success(avatarUrl);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("更新头像失败：" + e.getMessage());
        }
    }

    @GetMapping("/avatar/presets")
    public Result<?> getPresetAvatars() {
        try {
            Resource resource = new ClassPathResource("static/images/avatar");
            if (!resource.exists()) {
                return Result.error("头像目录不存在");
            }
            
            File avatarDir = resource.getFile();
            if (!avatarDir.isDirectory()) {
                return Result.error("头像路径不是目录");
            }
            
            String[] avatarFiles = avatarDir.list((dir, name) -> 
                name.toLowerCase().endsWith(".jpg") || 
                name.toLowerCase().endsWith(".png"));
                
            if (avatarFiles == null || avatarFiles.length == 0) {
                return Result.error("没有找到预设头像");
            }
            
            List<String> avatarUrls = Arrays.stream(avatarFiles)
                .map(name -> "/images/avatar/" + name)
                .collect(Collectors.toList());
                
            return Result.success(avatarUrls);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取预设头像失败：" + e.getMessage());
        }
    }

    @PostMapping("/goals")
    public Result<?> setUserGoal(
            @RequestParam Integer userId,
            @RequestBody UserGoal goal) {
        return userService.setGoal(userId, goal);
    }

    @GetMapping("/goals")
    public Result<?> getUserGoal(@RequestParam Integer userId) {
        return userService.getGoal(userId);
    }

    @ApiOperation("获取用户头像")
    @GetMapping("/avatar")
    public Result<?> getUserAvatar(@RequestParam Integer userId) {
        try {
            // 从数据库获取用户头像URL
            String avatarUrl = userMapper.getAvatarUrl(userId);
            if (avatarUrl == null || avatarUrl.isEmpty()) {
                avatarUrl = "/images/avatar/default.jpg"; // 返回默认头像
            }
            return Result.success(avatarUrl);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取用户头像失败：" + e.getMessage());
        }
    }
} 